﻿using Dapper;
using MediatR;
using MySql.Data.MySqlClient;
using SCM.API.Read.Application.Command.Sale;
using SCM.ErrorCode;
using SCM.Extensions;
using SCM.Infrastructure.Interface;
using System.Text;

namespace SCM.API.Read.Application.Handler.Sale
{
    public class GetProductHandler : IRequestHandler<GetProductCommand, APIResult<SaleProductDTO>>
    {
        IDatabaseContext db;

        public GetProductHandler(IDatabaseContext db)
        {
            this.db = db;
        }

        public async Task<APIResult<SaleProductDTO>> Handle(GetProductCommand request, CancellationToken cancellationToken)
        {
            APIResult<SaleProductDTO> res = new APIResult<SaleProductDTO>();

            var sqlBuilder = new StringBuilder();

            sqlBuilder.Append(@"SELECT   a.ProductCode,
                                         a.ProductName,
                                         a.Specifications,
                                         a.ProductId,
                                         c.UnitId,
                                         c.UnitName,
                                         a.Price
                                FROM ProductModel a
                                JOIN UnitModel c ON a.UnitId = c.UnitId
                                WHERE a.IsDel = 0 AND c.IsDel = 0 ");



            var parameters = new DynamicParameters();

            var data = await db.DapperConnection.QueryAsync<SaleProductDTO>(sqlBuilder.ToString(), parameters);


            res.Msg = "显示成功";
            res.Code = APIEnum.Success;
            res.Datas = data.ToList();
            return res;
        }
    }
}
